<script setup>
import HeaderNavTabarSvg from '@/components/HeaderNavTabarSvg/HeaderNavTabar.vue'
import { onLoad, onShow } from '@dcloudio/uni-app'

import AuditApplicationSteps from '@/components/audit/function/auditApplicationSteps.vue'
import DescriptionAttachment from '@/components/audit/function/descriptionAttachment.vue'
import { ref, watch, computed } from 'vue'
import dayjs from 'dayjs'
import optionDeptPerson from '@/store/modules/optionDeptPerson'
import { addFinancialApplyControllerApi } from '@/api/attendance'
import { getUserProfile } from '@/api/system/user'
import approvalProcessState from '@/store/modules/approvalProcess'
import { isObjectValuesNotEmpty } from '@/utils/objIsnull.js'
import { getWorkApi } from '@/api/customer.js'
import store from '@/store'

const title = ref('油费报销申请')
const customerPickerRef = ref(null) // 这个时候获取了子组件 Comp
const btnZIndex = ref(99) // 底部按钮层级
const entertainDateRef = ref(null)
const ItemRequisitionList = ref({
  deptName: '',
  serviceObject: [
    {
      deptName: '',
      deptId: '',
    },
  ], //报销人部门
  position: '', // 拜访记录
  applyId: '', // 拜访记录id
  reason: '',
  paymentMethod: '',
  escorts: [],
  itemRequisitionDetail: [
    {
      key: '',
      value: '',
    },
  ],
  money: '',
  remark: '',
})
watch(
  () => ItemRequisitionList.value.itemRequisitionDetail,
  (newProps) => {
    // 费用汇总
    ItemRequisitionList.value.money = newProps.reduce((acc, curr) => acc + Number(curr.value), 0)
  },
  {
    deep: true,
  }
)
const userId = ref(null)
const deptId = ref(null)
let attchment = ref([])
const getDesignDrawingsEmit = (emit) => {
  attchment.value = emit
}
const goHistoryView = () => {
  uni.navigateTo({
    url: '/components/TypeDefineModel?type=油费报销申请&apiName=财务',
  })
}
const clickSave = async () => {
  const RequiredItemList = JSON.parse(JSON.stringify(ItemRequisitionList.value))
  delete RequiredItemList.remark
  // console.log(RequiredItemList, 'RequiredItemList')
  if (isObjectValuesNotEmpty(RequiredItemList)) {
    let params = {
      paymentMethod: ItemRequisitionList.value.paymentMethod,
      date: dayjs(ItemRequisitionList.value.date).format('YYYY-MM-DD hh:mm:ss'),
      reason: ItemRequisitionList.value.reason,
      details: JSON.stringify(ItemRequisitionList.value.itemRequisitionDetail),
      money: ItemRequisitionList.value.money,
      remark: ItemRequisitionList.value.remark,
      personnel: JSON.stringify(ItemRequisitionList.value.escorts),
      position: ItemRequisitionList.value.position, // 拜访记录
      applyId: ItemRequisitionList.value.applyId, //拜访记录id
      ruleId: 'caigou',
      type: '油费报销申请',
      attchment: JSON.stringify(attchment.value),
      userId: userId.value,
      deptId: deptId.value,
      serviceObject: JSON.stringify(ItemRequisitionList.value.serviceObject),
      // deptId: ItemRequisitionList.value.deptId,
      approve: approvalProcessState.state.approvalProcess,
    }
    console.log(params, '油费报销申请提交params')

    let { code } = await addFinancialApplyControllerApi(params)
    if (code === 200) {
      uni.showToast({
        title: '提交成功',
        duration: 1500,
        icon: 'success',
      })
      setTimeout(() => {
        uni.navigateBack()
      }, 1000)
    }
  } else {
    uni.showToast({
      title: '请输入完整数据',
      icon: 'error',
    })
  }
}

const formatter = (type, value) => {
  if (type === 'year') {
    return `${value}年`
  }
  if (type === 'month') {
    return `${value}月`
  }
  if (type === 'day') {
    return `${value}日`
  }
  if (type === 'hour') {
    return `${value}时`
  }
  if (type === 'minute') {
    return `${value}分`
  }
  return value
}

const escortsFn = () => {
  uni.navigateTo({
    url: '/components/OptionDeptPerson/index?type=person&isDanXuan=1',
  })
}
const withSealFn = () => {
  uni.navigateTo({
    url: '/components/OptionDeptPerson/deptName?type=dept',
  })
}

// 去拜访列表页面
const toVisitListFn = () => {
  if (!ItemRequisitionList.value.customerId) {
    uni.showToast({
      title: '请先选择拜访客户',
      icon: 'none',
    })
  } else {
    // isApplyPage 1 代表申请页面跳转到拜访列表
    uni.navigateTo({
      url:
        '/pages/visit/visitList?isApplyPage=1&customerId=' + ItemRequisitionList.value.customerId,
    })
  }
}
const entertainDateFn = () => {
  entertainDateRef.value.open()
}
let entertainDatePicker = dayjs()
const entertainDateConfirm = (obj) => {
  ItemRequisitionList.value.date = dayjs(obj.value).format('YYYY-MM-DD')
}

const copyDetailItem = () => {
  ItemRequisitionList.value.itemRequisitionDetail.push({
    key: '',
    value: '',
  })
}
const deleteDetailItem = (index) => {
  ItemRequisitionList.value.itemRequisitionDetail.splice(index, 1)
}
const getUserProfileFn = async () => {
  let { code, data } = await getUserProfile()
  if (code === 200) {
    userId.value = data.userId
    deptId.value = data.deptId
  }
}

// 打开模态窗
const toggle = () => {
  customerPickerRef.value.toggle('bottom') // 调用子组件的 show 方法
  btnZIndex.value = 0
}

const closePop = () => {
  btnZIndex.value = 99
}

// 客户信息
let customerList = ref([])
// 获取客户下拉菜单数据
const getWorkApiData = async (v = '') => {
  let params = {
    customerName: v,
  }
  let { code, data } = await getWorkApi(params)
  if (code == 200) {
    data.forEach((v) => {
      // 过滤掉 null
      customerList.value.push({
        label: [v.primaryClassification, v.customerName].filter((item) => item != null).join('/'),
        value: v.customerId,
      })
    })
    store.commit('setCustomerList', customerList.value)
  }
}

// 选择的客户数据
const getVlaue = (v) => {
  ItemRequisitionList.value.customerId = v.value
  ItemRequisitionList.value.customerName = v.label
  customerPickerRef.value.closePop()
  btnZIndex.value = 99
}

onShow(() => {
  // 监听事件 获取选择的拜访记录
  uni.$on('getVisitData', (data) => {
    ItemRequisitionList.value.date = data[0].updateTime
    ItemRequisitionList.value.position = data[0].customerName
    ItemRequisitionList.value.applyId = data[0].id
  })

  // 监听事件 获取选择的人员
  uni.$on('getOptionPerson', (data) => {
    // console.log(data, '人员data')
    ItemRequisitionList.value.escorts = data.map((v) => {
      return {
        userId: v.userId,
        nickName: v.nickName,
      }
    })
  })

  // 监听事件 获取选择的部门
  uni.$on('getOptionDept', (data) => {
    // console.log(data, '部门data')
    ItemRequisitionList.value.deptName = data.label
    // ItemRequisitionList.value.deptId = data.id ? data.id : data.depId // id 子部门id depId部门id
    // 报销人的部门
    ItemRequisitionList.value.serviceObject[0].deptName = data.label
    ItemRequisitionList.value.serviceObject[0].deptId = data.deptId
    // ItemRequisitionList.value.serviceObject = data.map((v) => {
    // 	return {
    // 		deptId: v.id ? v.id : v.depId,
    // 		deptName: v.label,
    // 	}
    // })
  })

  getWorkApiData()
})

onLoad(() => {
  getUserProfileFn()
})
</script>

<template>
  <view>
    <HeaderNavTabarSvg :title="title">
      <image class="bukaSvg" src="/static/icon/auditSVG/buka.svg" @tap="goHistoryView"></image>
    </HeaderNavTabarSvg>

    <view class="picker-content" @tap="withSealFn">
      <view class="measurement-info-list">
        <text class="info-list-left isrequired">部门</text>
        <view class="info-list-right">
          <view v-if="ItemRequisitionList.deptName" class="uni-input"
            >{{ ItemRequisitionList.deptName }}
          </view>
          <view v-else class="uni-inputs">请选择</view>

          <i class="iconfont icon-youjiantou"></i>
        </view>
      </view>
    </view>

    <view class="picker-content" @tap="escortsFn">
      <view class="measurement-info-list">
        <text class="info-list-left isrequired">报销人</text>
        <view class="info-list-right">
          <view
            v-if="ItemRequisitionList.escorts.length > 0"
            v-for="(item, index) in ItemRequisitionList.escorts"
            :key="index"
            class="uni-input"
            >{{ item.nickName }}
            &nbsp
          </view>
          <view v-else class="uni-inputs">请选择</view>
          <i class="iconfont icon-youjiantou"></i>
        </view>
      </view>
    </view>

    <view class="textarea-box">
      <text class="info-list-left isrequired">报销事由</text>
      <textarea
        v-model="ItemRequisitionList.reason"
        class="textinfo-list"
        placeholder="请输入"
      ></textarea>
    </view>

    <view
      class="detail-itemRequisition"
      v-for="(item, index) in ItemRequisitionList.itemRequisitionDetail"
      :key="index"
    >
      <view class="detail-item">
        <text class="info-list-left isrequired" style="margin-top: 24rpx">{{
          index > 0 ? `费用明细${index + 1}` : '费用明细'
        }}</text>
        <p class="detail-utils">
          <text @tap="copyDetailItem">复制</text>
          <text
            @tap="deleteDetailItem(index)"
            v-if="ItemRequisitionList.itemRequisitionDetail.length > 1"
            >删除</text
          >
        </p>
      </view>

      <view class="picker-content">
        <view class="measurement-info-list">
          <view class="info-list-right">
            <view class="info-content" style="display: flex; align-items: center">
              <input
                adjust-position
                type="text"
                :placeholder="index > 0 ? `请输入类目${index + 1}` : '请输入类目'"
                v-model="item.key"
              />
            </view>
          </view>
          <view class="info-list-right">
            <view class="info-content" style="display: flex; align-items: center">
              :
              <input
                adjust-position
                type="number"
                class="uni-input"
                placeholder="请输入"
                v-model="item.value"
              />
              <p style="font-size: 28rpx; line-height: 1.4em">元</p>
            </view>
          </view>
        </view>
      </view>
    </view>

    <view class="picker-content">
      <view class="measurement-info-list">
        <text class="info-list-left isrequired">费用汇总</text>
        <view class="info-list-right">
          <view class="info-content" style="display: flex; align-items: center">
            <input
              adjust-position
              type="number"
              class="uni-input"
              placeholder="请先输入费用明细"
              v-model="ItemRequisitionList.money"
              disabled
            />
            <p style="font-size: 28rpx; line-height: 1.4em">元</p>
          </view>
        </view>
      </view>
    </view>
    <view class="picker-content">
      <view class="measurement-info-list">
        <text class="info-list-left isrequired">支出方式</text>
        <view class="info-list-right">
          <view class="info-content">
            <input
              adjust-position
              type="text"
              class="uni-input"
              placeholder="请输入"
              v-model="ItemRequisitionList.paymentMethod"
            />
          </view>
        </view>
      </view>
    </view>
    <MyPicker
      @getVlaue="getVlaue"
      @closePop="closePop"
      ref="customerPickerRef"
      popupTitle="请选择客户名称"
    >
      <view class="picker-content" @tap="toggle">
        <view class="measurement-info-list">
          <text class="info-list-left isrequired">拜访客户</text>
          <view class="info-list-right">
            <view v-if="ItemRequisitionList.customerName" class="uni-input">
              {{ ItemRequisitionList.customerName }}
            </view>
            <view class="uni-inputs" v-else>请选择</view>
            <i class="iconfont icon-youjiantou"></i>
          </view>
        </view>
      </view>
    </MyPicker>
    <view class="picker-content" @tap="toVisitListFn">
      <view class="measurement-info-list">
        <text class="info-list-left isrequired">拜访记录ID</text>
        <view class="info-list-right">
          <view v-if="ItemRequisitionList.applyId" class="uni-input"
            >{{ ItemRequisitionList.applyId }}
          </view>
          <view v-else class="uni-inputs">请选择</view>

          <i class="iconfont icon-youjiantou"></i>
        </view>
      </view>
    </view>
    <view class="picker-content" @tap="entertainDateFn">
      <view class="measurement-info-list">
        <text class="info-list-left isrequired">报销日期</text>
        <view class="info-list-right">
          <view class="uni-input" v-if="ItemRequisitionList.date"
            >{{ ItemRequisitionList.date }}
          </view>
          <view class="uni-inputs" v-else>请先选择拜访记录</view>
        </view>
      </view>
    </view>
    <!-- 		<uv-datetime-picker
		  ref="entertainDateRef"
		  v-model="entertainDatePicker"
		  :formatter="formatter"
		  mode="date"
		  @confirm="entertainDateConfirm"
		/> -->
    <view class="textarea-box">
      <text class="info-list-left">路线</text>
      <textarea
        v-model="ItemRequisitionList.remark"
        class="textinfo-list"
        placeholder="请输入"
      ></textarea>
    </view>

    <!--    说明附件-->
    <DescriptionAttachment
      fileTitle="报销凭证上传"
      @getDesignDrawingsEmit="getDesignDrawingsEmit"
    />
    <!--    审批流程-->
    <AuditApplicationSteps :ruleId="'caigou'" :purchaseMoney="ItemRequisitionList.purchaseMoney" />
    <!--    底部占位符-->
    <view class="blank"></view>
    <!--    保存-->
    <view class="buttonContainer">
      <button class="buttonClass" @click="clickSave">提交</button>
    </view>
  </view>
</template>

<style lang="scss" scoped>
@import '@/static/style/index.scss';

.bukaSvg {
  width: 32rpx;
  height: 32rpx;
}

.buttonContainer {
  position: fixed;
  bottom: 0;
  display: flex;
  justify-content: center;
  width: 100%;
  align-items: center;
  padding: 16rpx;
  background-color: #fff;
}

.buttonClass {
  display: flex;
  width: 686rpx;
  height: 72rpx;
  justify-content: center;
  align-items: center;
  background: #165dff;
  border-radius: 16rpx;
  color: #fff;
  font-size: 32rpx;
  //margin-top: 40rpx;
  overflow: hidden;
}

.uni-inputs {
  color: #86909c !important;
}

.uni-input {
  text-align: right;
  font-size: 28rpx;
}

.info-list-left {
  // @include font-color-auxiliary;
  color: #1d2129;
  font-size: $font-size-base;
}

.blank {
  height: calc(72rpx + 32rpx + 20rpx);
}

.textarea-box {
  background: #fff;
  padding: 20rpx;
  margin-top: 20rpx;

  .info-list-left {
    // @include font-color-auxiliary;
    color: #1d2129;
    font-size: $font-size-base;
  }

  .textinfo-list {
    margin-top: 20rpx;
    width: 100%;
    height: 200rpx;
  }
}

.bukabanci {
  .info-content {
    color: #86909c !important;
  }

  .info-list-left {
    // @include font-color-auxiliary;
    color: #86909c !important;
  }
}

.textarea-box {
  background: #fff;
  padding: 20rpx;
  margin-top: 20rpx;

  .info-list-left {
    // @include font-color-auxiliary;
    color: #1d2129;
    font-size: $font-size-base;
  }

  .textinfo-list {
    margin-top: 20rpx;
    width: 100%;
    height: 200rpx;
  }
}

.popup-content {
  background: #f7f8fa;

  .header-box {
    padding: 30rpx 20rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;

    p {
      color: #1d2129;
      font-size: 34rpx;
      font-weight: 500;
    }

    .module-image-ba {
      border-radius: 32rpx;
      background: #f2f3f5;
      width: 45rpx;
      height: 45rpx;
      display: flex;
      align-items: center;
      justify-content: center;

      image {
        width: 32rpx;
        height: 32rpx;
      }
    }
  }

  .card-list {
    display: flex;
    align-items: center;
    flex-direction: column;
    padding: 20rpx 30rpx;
    box-sizing: border-box;

    .list {
      box-shadow: 0 4rpx 16rpx 0 #0000000d;
      box-sizing: border-box;
      width: 100%;
      background: #fff;
      padding: 16rpx 24rpx;
      border-radius: 8rpx;
      margin-bottom: 10rpx;

      h4 {
        color: #1d2129;
        font-size: 32rpx;
        font-weight: 400;
      }

      p {
        color: #86909c;
        font-size: 24rpx;
        font-weight: 400;
        margin-top: 10rpx;
      }
    }
  }
}

.detail-itemRequisition {
  .detail-item {
    padding: 10rpx 30rpx;
    @include flex($align: center, $justify: space-between);

    .detail-utils {
      @include flex($align: center, $justify: space-between);
      width: 150rpx;
      color: #165dff;
    }
  }

  .text-info {
    color: #86909c;
    padding: 20rpx 30rpx;
    display: inline-block;
  }
}

.measurement-info-list {
  @include flex($align: center, $justify: space-between);
  padding: $spacing-row-base;
  background: #fff;
  margin-top: 16rpx;

  .info-list-left {
    // @include font-color-auxiliary;
    color: #1d2129;
    font-size: $font-size-base;
  }

  .info-list-right {
    @include flex($align: center);

    .info-content {
      @include textStyleBase;
      font-size: 34rpx;
    }

    .iconfont {
      margin-left: 16rpx;
      // @include font-color-auxiliary;
      color: $uni-fc-fu-lin;
    }
  }

  .unit {
    // @include font-color-auxiliary;
    color: $uni-fc-fu-lin;
  }
}
</style>
